package com.heerlin.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //创建数据库会话sqlSessionFactory
            String resource = "mybatis-config.xml";
            //输入流
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 定义一个公共的静态方法，用于获取 SqlSession 对象
    public static SqlSession getSqlSession() {
        // 打开一个新的 SqlSession 会话
        return sqlSessionFactory.openSession();
    }
}
